package study

// 使用map实现的一个简单本地缓存类
import (
	"fmt"
	"sync"
	"time"
)

type Cache struct {
	data     map[string]interface{}
	mutex    sync.RWMutex
	duration time.Duration
}

func NewCache(duration time.Duration) *Cache {
	return &Cache{
		data:     make(map[string]interface{}),
		duration: duration,
	}
}

func (c *Cache) Get(key string) (interface{}, bool) {
	c.mutex.RLock()
	defer c.mutex.RUnlock()

	value, ok := c.data[key]
	if !ok {
		return nil, false
	}

	// expirationTime, ok := value.(time.Time)
	// if !ok || time.Now().After(expirationTime) {
	// 	delete(c.data, key)
	// 	return nil, false
	// }

	return value, true
}

func (c *Cache) Set(key string, value interface{}) {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	c.data[key] = value
	time.AfterFunc(c.duration, func() {
		c.mutex.Lock()
		defer c.mutex.Unlock()

		delete(c.data, key)
	})
}

func TestCache() {
	cache := NewCache(5 * time.Second)

	cache.Set("key1", "value1")
	cache.Set("key2", "value2")

	if value, ok := cache.Get("key1"); ok {
		fmt.Println("Value for key1:", value)
	}

	time.Sleep(6 * time.Second)

	if _, ok := cache.Get("key1"); !ok {
		fmt.Println("Key1 has expired or does not exist.")
	}
}
